//
//  UUKeeperManager.m
//  UUCharterSupplier
//
//  Created by ZhangAo on 24/01/2018.
//  Copyright © 2018 UUCharter. All rights reserved.
//

#import "UUKeeperManager.h"
#import "UUSupplierConstants.h"
#import "UUKeeperUtility.h"
#import <UUFoundation/UUIncrementDataManager.h>
#import <UUFoundation/DKDataManager.h>
#import "UUKeeperRequestModel.h"
#import "UUKeeperAddRequestModel.h"
#import "UUKeeperEditRequestModel.h"
#import "UUKeeperDeleteRequestModel.h"
#import "UUKeeperUnbundingVerifyCodeRequestModel.h"

@interface UUKeeperManager ()

@property (nonatomic, strong) UUIncrementDataManager *keeperDataManager;

@end

@implementation UUKeeperManager

- (instancetype)init {
    self = [super init];
    if (self) {
        self.keeperDataManager = [UUIncrementDataManager managerWithConfiguration:
                                  [UUIncrementDataManagerConfiguration configurationWithRequestModelClass:[UUKeeperRequestModel class]
                                                                                           storeContainer:[UUKeeperUtility keeperDefaults]]];
    }
    return self;
}

- (void)asyncUpdateKeepers {
    WEAK_SELF();
    [self.keeperDataManager asyncIncrementUpdateWithCompleteBlock:^(BOOL hadUpdate, NSArray<id> *insert, NSArray<id> *delete, NSError *error) {
        if (hadUpdate) {
            NSNumber *currentUserId = [UUKeeperUtility currentUserId];
            for (id userId in insert) {
                if ([userId isEqual:currentUserId]) {
                    if ([weakSelf fetchKeeperWithKeeperId:currentUserId].roleId != [UUKeeperUtility currentUserRole]) {
                        [UUKeeperUtility logoutCurrentUser];
                        return;
                    } else {
                        [weakSelf notifyObserversWithSelector:@selector(keeperManagerDidupdateCurrentUser) withObject:nil];
                    }
                    
                    break;
                }
            }
            
            [weakSelf notifyObserversWithSelector:@selector(keeperManagerDidUpdateKeepers) withObject:nil];
        }
    }];
}

- (NSArray<id> *)fetchKeepers {
    NSArray<NSNumber *> *keepers = [UUKeeperModel searchColumn:@"id" where:nil orderBy:nil offset:0 count:0];
    return keepers;
}

- (UUKeeperModel *)fetchKeeperWithKeeperId:(id)keeperId {
    return (UUKeeperModel *)[self.keeperDataManager fetchModelWithPrimaryKeyValue:keeperId];
}

- (void)asyncAddKeeperWithName:(NSString *)name
                        mobile:(NSString *)mobile
                      fleetIds:(NSString *)fleetIds
                        roleId:(UUPermissionRoleType)roleId
                 completeBlock:(void (^)(NSError *error))completeBlock {
    UUKeeperAddRequestModel *requestModel = [UUKeeperAddRequestModel new];
    requestModel.name = name;
    requestModel.mobile = mobile;
    requestModel.fleetIds = fleetIds;
    requestModel.roleId = roleId;
    
    WEAK_SELF();
    [[DKDataManager new] requestWithRequestModel:requestModel completedBlock:^(DKResponseModel *responseModel, NSError *error) {
        if (error == nil) {
            [weakSelf asyncUpdateKeepers];
        }
        
        BLOCK_SAFE_CALLS_In_Main_Queue(completeBlock, error);
    }];
}

- (void)asyncUpdateKeeperWithKeeperId:(id)keeperId
                                 name:(NSString *)name
                               mobile:(NSString *)mobile
                             fleetIds:(NSString *)fleetIds
                               roleId:(UUPermissionRoleType)roleId
                        completeBlock:(void (^)(NSError *error))completeBlock {
    UUKeeperEditRequestModel *requestModel = [UUKeeperEditRequestModel new];
    requestModel.id = keeperId;
    requestModel.name = name;
    requestModel.mobile = mobile;
    requestModel.fleetIds = fleetIds;
    requestModel.roleId = roleId;
    
    WEAK_SELF();
    [[DKDataManager new] requestWithRequestModel:requestModel completedBlock:^(DKResponseModel *responseModel, NSError *error) {
        if (error == nil) {
            [weakSelf asyncUpdateKeepers];
        }
        
        BLOCK_SAFE_CALLS_In_Main_Queue(completeBlock, error);
    }];
}

- (void)asyncDeleteKeeperWithKeeperId:(NSNumber *)keeperId
                           verifyCode:(NSString *)verifyCode
                        completeBlock:(void (^)(NSError *error))completeBlock {
    UUKeeperDeleteRequestModel *requestModel = [UUKeeperDeleteRequestModel new];
    requestModel.keeperId = keeperId;
    requestModel.verifyCode = verifyCode;
    
    WEAK_SELF();
    [[DKDataManager new] requestWithRequestModel:requestModel completedBlock:^(DKResponseModel *responseModel, NSError *error) {
        if (error == nil) {
            [weakSelf asyncUpdateKeepers];
        }
        
        BLOCK_SAFE_CALLS_In_Main_Queue(completeBlock, error);
    }];
}

- (void)asyncSendUnbundingVerifyCodeWithCompleteBlock:(void (^)(NSString *mobile, NSError *))completeBlock {
    UUKeeperUnbundingVerifyCodeRequestModel *requestModel = [UUKeeperUnbundingVerifyCodeRequestModel new];
    
    [[DKDataManager new] requestWithRequestModel:requestModel completedBlock:^(DKResponseModel *responseModel, NSError *error) {
        UUKeeperUnbundingVerifyCodeResponseModel *unbundingVerifyCodeResponseModel = (UUKeeperUnbundingVerifyCodeResponseModel *)responseModel;
        BLOCK_SAFE_CALLS_In_Main_Queue(completeBlock, unbundingVerifyCodeResponseModel.mobile, error);
    }];
}

@end
